package electricity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import electricity.domain.Permission;
import electricity.domain.Role;
import electricity.domain.RolePermission;
import electricity.mapper.PermissionMapper;
import electricity.mapper.RoleMapper;
import electricity.mapper.RolePermissionMapper;
import electricity.mapper.UserRoleMapper;
import electricity.service.PermissionService;
import cn.dev33.satoken.stp.StpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private RoleMapper roleMapper;

    public PermissionServiceImpl(PermissionMapper permissionMapper, RolePermissionMapper rolePermissionMapper, UserRoleMapper userRoleMapper) {
        this.permissionMapper = permissionMapper;
        this.rolePermissionMapper = rolePermissionMapper;
        this.userRoleMapper = userRoleMapper;
    }
    @Override
    public List<String> getCurrentAccountPermissionCodes() {

        String role = StpUtil.getSession().getString("role");
        if (role != null) {
            return baseMapper.selectPermissionCodesByRole(role);
        }
        return null;
    }

    @Override
    public List<String> getPermissionCodesByUserId(Integer userId) {
        // 根据用户ID获取角色ID
        Integer roleId = userRoleMapper.selectRoleIdByUserId(userId);
        if (roleId == null) {
            return null;
        }
        // 根据角色ID获取权限ID列表
        QueryWrapper<RolePermission> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id", roleId);
        List<RolePermission> rolePermissions = rolePermissionMapper.selectList(wrapper);
        List<Integer> permissionIds = rolePermissions.stream()
                .map(RolePermission::getPermissionId)
                .collect(Collectors.toList());
        // 根据权限ID列表获取权限码列表
        QueryWrapper<Permission> permissionWrapper = new QueryWrapper<>();
        permissionWrapper.in("id", permissionIds);
        List<Permission> permissions = permissionMapper.selectList(permissionWrapper);
        return permissions.stream()
                .map(Permission::getPermissionCode)
                .collect(Collectors.toList());
    }

    @Override
    public void addRole(Role role) {
// 设置创建时间
        role.setCreateTime(LocalDateTime.now());
        // 插入数据库
        int rows = roleMapper.insert(role);
        if (rows <= 0) {
            throw new RuntimeException("新增角色失败");
        }
    }

    @Override
    public void updateRole(Role role) {
// 不更新创建时间（避免覆盖）
        role.setCreateTime(null);
        // 更新数据库
        int rows = roleMapper.updateById(role);
        if (rows <= 0) {
            throw new RuntimeException("更新角色失败，角色不存在");
        }
    }

    @Override
    public void deleteRole(Integer id) {
        // 1. 删除角色与权限的关联
        rolePermissionMapper.deleteByRoleId(id);
        // 2. 删除角色本身
        int rows = roleMapper.deleteById(id);
        if (rows <= 0) {
            throw new RuntimeException("删除角色失败，角色不存在");
        }
    }

    @Override
    public List<Integer> getRolePermissionIds(Integer roleId) {
        return rolePermissionMapper.selectPermissionIdsByRoleId(roleId);
    }

    @Override
    public void saveRolePermissions(Integer roleId, List<Integer> permissionIds) {
        // 1. 先删除旧的关联
        rolePermissionMapper.deleteByRoleId(roleId);

        // 2. 批量插入新的关联
        if (permissionIds != null && !permissionIds.isEmpty()) {
            List<RolePermission> rolePermissions = new ArrayList<>();
            for (Integer permissionId : permissionIds) {
                RolePermission rp = new RolePermission();
                rp.setRoleId(roleId);
                rp.setPermissionId(permissionId);
                rolePermissions.add(rp);
            }
            rolePermissionMapper.batchInsert(rolePermissions);
        }
    }

    @Override
    public List<Permission> getAllPermissions() {
        return permissionMapper.selectAllPermissions();
    }
}
